<template>
    <view>
        <view style="position: sticky; top: 0rpx; left: 0; z-index: 1">
            <view class="search-content">
                <view class="search-content-con">
                    <u-search inputAlign="center" placeholder="请输入商品名称查询" bg-color="#F7F8FA" v-model="searchKeyword"
                        :height="56" :maxlength="20" @search="searchInputHandle" @custom="searchInputHandle"
                        :action-style="searchActionStyle"></u-search>
                </view>
            </view>
        </view>

        <view v-if="dataList.length">
            <view v-for="(list, index) in dataList" :key="index">
                <view class="products-wrap">
                    <view v-for="(item2, index2) in list.dataList" :key="index2">
                        <goods-card v-if="!cardShow" :url="`/pages/goods-details/goods-details?id=${item2.id}`"
                            :cover="item2.banner.split(',')[0]" :title="item2.name" :price="reGoodsPrice(item2)"
                            :detail="item2" @addCart="apiAddCart11"></goods-card>
                        <!-- <goodsCardSmall v-if="cardShow" :url="`/pages/goods-details/goods-details?id=${item2.id}`"
                            :cover="item2.banner.split(',')[0]" :title="item2.name" :price="reGoodsPrice(item2)"
                            :detail="item2" @addCart="addCart"></goodsCardSmall> -->
                    </view>
                </view>
            </view>
        </view>
        <!-- <purchaseGoods :showModal="showPay" :detail="goodsData" @close="onclose" @submit="submit" :type="type">
        </purchaseGoods> -->
        <co-load-more :type="loadingType"><co-empty slot="empty" model="data"
                paddingTop="80rpx"></co-empty></co-load-more>
    </view>
</template>

<script>
import { apiCategoryGoods } from '@/api/goods'
import purchaseGoods from '@/components/purchase-goods/purchase-goods'
import goodsCardSmall from '@/components/goods-card-small/goods-card-small'
import tabbarPage from '@/mixins/tabbarPage'
import { appOnLaunch } from '@/utils/appGlobalLifeCycle'
import { apiAddCart } from '@/api/shoppingCart'
import { UPDATE_SHOPPING_CART } from '@/types/globalEventName'
import RetailPriceSign from './components/retail-price-sign.vue'
import { getList as apiGetList, bannerProxyQueryPage } from '@/api/goods.js'
// 不允许请求的type
const noRequestType = [1, 2, 3]
/**
 * 采用懒更新方案，只有当供应商变了，并且进入当前页面，才会更新数据
 * */
export default {
    data() {
        return {
            newPublish: 0,
            hotSalesRanking: 0,
            listType: null,// 0今日推荐 // 1 店长推荐
            goodsData: {},
            categoryList: [],
            shouldUpdate: true, // 是否应该更新
            getLoading: false, // 是否正在刷新列表
            showPay: false,
            type: 1,
            dataList: [],
            searchKeyword: '',
            realSearchKeyword: '',
            searchActionStyle: {
                color: '#fff',
                fontSize: '28rpx',
                background:
                    'linear-gradient( 323deg, #FF4564 8%, #F14141 30%, #FC843B 100%)',
                borderRadius: '200rpx 200rpx 200rpx 200rpx',
                width: '112rpx',
                height: '56rpx',
                lineHeight: '56rpx'
            },
            loadingType: 999,
            current: 0,
            secondCurrent: 0,
            categoryIds: [],
            stairCategoryId: '',
            pageNum: 1,
            cardShow: false,
            qieHuanList: [
                'https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/a03bf10a98cb4fdf89361c311029c9ccqiehuancard.png',
                'https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/5d4a9f4060874c73b71d012fd27c7184qihuan.png'
            ],
            secondCategoryList: [],
            options: {},
            listBannerList: [],
            indicatorDots: true,
            autoplay: true,
            interval: 2000,
            duration: 500
        }
    },
    components: {
        RetailPriceSign,
        purchaseGoods,
        goodsCardSmall
    },
    onLoad(options) {
        this.options = options
        if (this.shouldUpdate && !this.getLoading) {
            // this.getProductsList()
            // this.getListBannerList()
            this.listTypeDetail = JSON.parse(options.data)
            uni.setNavigationBarTitle({
                title: this.listTypeDetail.title
            })
            this.unlockInit()
        }

    },
    onShow() {
        if (!this.$store.getters.isLogin) {
            appOnLaunch()
            return
        }
    },
    mixins: [tabbarPage],
    computed: {},
    onReachBottom() {
        this.getList()
    },
    methods: {
        getListBannerList() {
            bannerProxyQueryPage({ banner: 1 }).then((res) => {
                console.log(res, '==-=-=--=-')
                if (res.data.code == 200) {
                    this.listBannerList = res.data.data
                }
            })
        },
        secondChange(index) {
            this.pageNum = 1
            this.dataList = []
            this.secondCurrent = index
            this.categoryIds = [this.secondCategoryList[index]?.cid] || []
            this.loadingType = 999
            this.getList()
        },
        change(index) {
            this.secondCategoryList = []
            this.categoryIds = []
            this.current = index
            this.secondCurrent = 0
            this.pageNum = 1
            this.dataList = []
            this.stairCategoryId = this.categoryList[index].cid
            this.secondCategoryList =
                index == 0 ? [] : [...(this.categoryList[index]?.categors || [])]
            this.categoryIds = index == 0 ? [] : [this.secondCategoryList[0]?.cid]

            this.loadingType = 999
            this.getList()
        },
        reGoodsPrice(item) {
            return item.skuChildList[0].purchasePrice
        },
        // 搜索框点击搜索
        searchInputHandle(e) {
            console.log(e)
            if (this.realSearchKeyword !== e) {
                this.realSearchKeyword = e
                this.loadingType = 999
                this.unlockInit()
            }
        },
        onclose(show) {
            this.showPay = show
            uni.showTabBar()
        },
        submit(data) {
            uni.showTabBar()
            if (this.type == 1) {
                this.apiAddCart(data)
            } else {
                this.$u.route('pages/place-order/submit-order', {
                    val: JSON.stringify(data.val)
                })
            }
            this.showPay = false
        },
        // 添加商品到购物车
        apiAddCart11(data) {

            uni.showLoading({
                mask: true
            })
            apiAddCart(data)
                .then((res) => {
                    console.log(res,'dddddddddddddd');
                    
                    let { state, msg } = res.data
                    uni.hideLoading()
                    if (state === 'OK') {
                        console.log(res,'dddddddddddddd');
                        uni.$emit(UPDATE_SHOPPING_CART)
                        this.$store.dispatch('getCartNum')
                        this.$am_toast.success('成功添加购物车')
                        this.$store.dispatch('getNoticeData')
                    } else {
                        this.$am_toast(msg)
                    }
                })
                .catch((err) => {
                    uni.hideLoading()
                    this.$am_toast.error('添加222失败，请重新尝试！')
                })
        },
        // 启用规格窗口
        addCart(type, val, num) {
            if (num) return
            this.goodsData = val
            this.showPay = true
            uni.hideTabBar()
            this.type = type
        },
        dataInit() {
            this.dataList = []
            this.pageNum = 1
        },
        unlockInit() {
            this.dataInit()
            this.getList()
        },
        getProductsList() {
            if (this.getLoading) return
            this.getLoading = true
            uni.showLoading({
                mask: true
            })
            apiCategoryGoods()
                .then((res) => {
                    let { state, data, msg } = res.data
                    if (state === 'OK') {
                        let categoryList = []

                        data[0].categoryEntityVOS.forEach((p1) => {
                            categoryList.push({
                                cid: p1.cid,
                                name: p1.name,
                                categors: p1.categors
                            })
                        })
                        this.categoryList = [{ name: '全部', cid: '' }, ...categoryList]
                        this.current = Number(this.options.firstIndex) + 1
                        this.secondCurrent = this.options.index

                        this.stairCategoryId = this.categoryList[this.current].cid
                        this.secondCategoryList =
                            this.current == 0
                                ? []
                                : [...(this.categoryList[this.current]?.categors || [])]
                        this.categoryIds =
                            this.current == 0
                                ? []
                                : [this.secondCategoryList[this.secondCurrent]?.cid]
                        this.getList()
                        uni.hideLoading()
                        this.shouldUpdate = false
                    } else {
                        uni.hideLoading()
                        this.$am_toast(msg)
                    }
                    this.getLoading = false
                })
                .catch((err) => {
                    console.log(err)
                    uni.hideLoading()
                    this.getLoading = false
                    this.$am_toast.error('查询失败')
                })
        },

        filterEmptyKeys(obj) {
            return Object.fromEntries(
                Object.entries(obj).filter(([key, value]) => key && value)
            );
        },
        getList() {
            // if (noRequestType.includes(this.loadingType)) {
            //     return
            // }
            // this.loadingType = 2
            console.log('调用获取数据')
            const params = {
                // newPublish: this.newPublish, //'新品发布',
                // hotSalesRanking: this.hotSalesRanking, // 热销排行
                // type: this.listType, // 今日推荐 // 1 店长推荐
                pageNum: this.pageNum,
                pageSize: 10,
                name: this.realSearchKeyword
            }
            console.log(params, '顶顶顶顶顶');

            apiGetList({ ...params, ...this.listTypeDetail })
                .then(({ data }) => {
                    if (data.state === 'OK') {
                        if (this.pageNum === 1) {
                            this.dataList.push({
                                banner: [],
                                dataList: data.data.list
                            })

                            // [...this.dataList, ...data.data.list]
                        } else {
                            this.dataList.push({
                                banner: this.listBannerList,
                                dataList: data.data.list
                            })
                        }
                        if (this.pageNum === 1 && this.dataList[0]?.dataList?.length == 0) {
                            this.loadingType = 1
                        } else if (data.data.totalPage == this.pageNum) {
                            this.loadingType = 3
                        } else {
                            this.loadingType = 999
                            this.pageNum++
                        }
                    }
                    uni.stopPullDownRefresh()
                })
                .catch((err) => {
                    console.log(err)
                    this.loadingType = 999
                    this.$am_toast.warning('查询失败，请重新尝试！')
                    uni.stopPullDownRefresh()
                })
        },
        // 购买
        goBuy(event) {
            let id = event.currentTarget.dataset.pid
            let stock = event.currentTarget.dataset.stockTotal
            if (stock === 0) return
            this.$u.route('pages/place-order/submit-order', { ids: id })
        }
    }
}
</script>

<style lang="scss" scoped>
$product-plr: 16rpx;

.products-wrap {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0 24rpx;
    border-radius: 16rpx;

    &.disabled {
        opacity: 0.5;
    }
}

.product-section-header {
    padding-top: 27rpx;
    padding-left: $product-plr;
    padding-right: $product-plr;
    font-size: 24rpx;
    color: #999999;
}

.search-content {
    display: flex;
    align-items: center;
    padding: 32rpx 24rpx;
    background-color: #fff;
    border-bottom: 2rpx solid #f5f5f5;
}

.search-content-con {
    flex: 1;
}

.list-change-bth {
    width: 10%;
    background: #fff;
    border-left: 1px solid #f5f5f5;
    justify-content: center;
}

.list-change-bth-img {
    width: 40rpx;
    height: 40rpx;
}

.list-banner-img {
    border-radius: 16rpx;
    object-fit: cover;
}
</style>